import { createRouter, createWebHashHistory } from "vue-router";
import store from 'src/store/index'
import { getToken } from "utils/auth";

const routes = [
  {
    path: "/",
    name: "home",
    redirect: '/index',
    component: () => import("../pages/home/home.vue"),
    children: [
      {
        path: "/index",
        name: "index",
        component: () => import("../pages/home/pages/index/index.vue"),
      },
      {
        path: "/ever-note",
        name: "everNote",
        component: () => import("../pages/home/pages/ever-note/ever-note.vue"),
      },
      {
        path: "/personal-center",
        name: "PersonalCenter",
        component: () => import("../pages/home/pages/personal-center/personal-center.vue"),
      }
    ]
  },
  {
    path: "/write-notes",
    name: "writeNotes",
    component: () => import("../pages/write-notes/write-notes.vue"),
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../pages/register/register.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../pages/login/login.vue"),
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../pages/404/404.vue"),
  },

];

const router = createRouter({
  history: createWebHashHistory(), // hash路由模式
  // history: createWebHistory(),  // history路由模式
  routes,
});

const whiteList = ["/login", "/register"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/index" });
    } else {
      if (Object.keys(store.state.user.userInfo).length == 0) {
        store.dispatch("user/getUserInfo")
      }
      console.log(store.state.permission.accessRoutes.length > 0)
      if (store.state.permission.accessRoutes.length > 0) {
        next();
      } else if (!store.state.permission.isGetAccessRoute) {
        const accessRoutes = await store.dispatch("permission/getMenus")
        console.log("🚀 ~ file: index.js:83 ~ router.beforeEach ~ accessRoutes", accessRoutes)
        accessRoutes.forEach(route => {
          router.addRoute("home", route);
        })
        next({ ...to, replace: true })
      } else {
        next();
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`);
    }
  }

});

export default router;
